/* eslint-disable */
<template>
  <div class="workorder-list">
    <el-card>
      <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:16px;">
        <div style="display:flex;align-items:center;gap:16px;">
          <el-input v-model="search" placeholder="搜索工单编号/描述/客户名/业务名" style="width:240px;" clearable @keyup.enter="loadData" />
          <el-select v-model="priorityFilter" placeholder="优先级筛选" style="width:120px;" clearable @change="loadData">
            <el-option :value="1" label="高" />
            <el-option :value="2" label="中" />
            <el-option :value="3" label="低" />
          </el-select>
        </div>
        <div>
          <el-upload :show-file-list="false" :before-upload="handleImport" accept=".xls,.xlsx">
            <el-button>导入</el-button>
          </el-upload>
          <el-button @click="handleExport">导出</el-button>
          <el-button v-if="authStore.user?.role === '管理员' || authStore.user?.role === '经理' || authStore.user?.role === '普通员工'" type="primary" @click="goAdd">新增工单</el-button>
        </div>
      </div>
      <el-table :data="list" border stripe style="width:100%;">
        <el-table-column prop="orderId" label="ID" width="80" />
        <el-table-column prop="orderNumber" label="工单编号" width="120" />
        <el-table-column prop="customerName" label="客户" width="120" />
        <el-table-column prop="businessName" label="业务" width="120" />
        <el-table-column prop="description" label="工单描述" />
        <el-table-column prop="priority" label="优先级" width="100">
          <template #default="{row}">
            <el-tag :type="priorityTag(row.priority)">{{ priorityText(row.priority) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="orderStatus" label="状态">
          <template #default="{row}">
            <el-tag :type="statusTag(row.orderStatus)">{{ statusText(row.orderStatus) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="接单时间" width="160">
          <template #default="{row}">
            {{ formatDateTime(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="actualCompleteTime" label="完成时间" width="160">
          <template #default="{row}">
            {{ formatDateTime(row.actualCompleteTime) }}
          </template>
        </el-table-column>
        <el-table-column label="完成用时" width="120">
          <template #default="{row}">
            {{ calculateTimeDiff(row.createTime, row.actualCompleteTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template #default="{row}">
            <el-button v-if="authStore.user?.role === '管理员' || authStore.user?.role === '经理' || authStore.user?.role === '客服' || (authStore.user?.role === '普通员工' && row.createdBy === authStore.user?.staffId)" size="small" @click="goEdit(row)">编辑</el-button>
            <el-button v-if="authStore.user?.role === '管理员' || authStore.user?.role === '经理'" size="small" type="danger" @click="handleDelete(row)">删除</el-button>
            <el-button size="small" type="success" @click="handleComplete(row)" v-if="row.orderStatus===0||row.orderStatus===1">完成</el-button>
            <el-button size="small" type="warning" @click="handleReturn(row)" v-if="row.orderStatus===0||row.orderStatus===1">退回</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-model:current-page="page"
        v-model:page-size="limit"
        :total="total"
        :page-sizes="[12,24,36,48]"
        layout="total, prev, pager, next, sizes"
        @current-change="loadData"
        @size-change="loadData"
        style="margin-top:16px;text-align:right;"
      />
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getWorkorders, deleteWorkorder, importWorkorders, exportWorkorders, completeWorkorder, returnWorkorder } from '@/api/workorder'
import { useAuthStore } from '@/stores/auth'
import { formatDateTime, calculateTimeDiff } from '@/utils/dateFormat'

const router = useRouter()
const list = ref([])
const total = ref(0)
const page = ref(1)
const limit = ref(12)
const search = ref('')
const priorityFilter = ref(null)
const authStore = useAuthStore()

const loadData = async () => {
  const res = await getWorkorders({ page: page.value, limit: limit.value, search: search.value, priority: priorityFilter.value })
  list.value = (res.records || []).map(item => ({
    ...item,
    id: item.id || item.orderId
  }))
  total.value = res.total || 0
}
onMounted(loadData)

const goAdd = () => router.push('/workorders/add')
const goEdit = row => router.push(`/workorders/edit/${row.id}`)
const handleDelete = row => {
  const id = Number(row.id)
  if (!id || isNaN(id)) {
    ElMessage.error('无效的ID，无法删除')
    return
  }
  ElMessageBox.confirm('确定要删除该工单吗？','提示',{type:'warning'}).then(async()=>{
    await deleteWorkorder(id)
    ElMessage.success('删除成功')
    loadData()
  })
}
const handleImport = async (file) => {
  await importWorkorders(file)
  ElMessage.success('导入成功')
  loadData()
  return false
}
const handleExport = async () => {
  const res = await exportWorkorders()
  const url = window.URL.createObjectURL(new Blob([res]))
  const link = document.createElement('a')
  link.href = url
  link.download = '工单数据.xlsx'
  link.click()
  window.URL.revokeObjectURL(url)
}
const handleComplete = async (row) => {
  await completeWorkorder(row.id)
  ElMessage.success('工单已完成')
  loadData()
}
const handleReturn = async (row) => {
  ElMessageBox.prompt('请输入退回原因','退回工单',{inputType:'textarea'}).then(async({ value })=>{
    await returnWorkorder(row.id, value)
    ElMessage.success('工单已退回')
    loadData()
  })
}
const statusText = (status) => {
  switch(status){
    case 0: return '新建';
    case 1: return '处理中';
    case 2: return '已完成';
    case 3: return '已退回';
    default: return '未知';
  }
}
const statusTag = (status) => {
  switch(status){
    case 0: return 'info';
    case 1: return 'warning';
    case 2: return 'success';
    case 3: return 'danger';
    default: return '';
  }
}
const priorityText = (priority) => {
  switch(priority){
    case 1: return '高';
    case 2: return '中';
    case 3: return '低';
    default: return '未知';
  }
}
const priorityTag = (priority) => {
  switch(priority){
    case 1: return 'danger';
    case 2: return 'warning';
    case 3: return 'info';
    default: return '';
  }
}
</script>

<style scoped>
.workorder-list {
  padding: 32px 0;
}
</style> 